//
//  LoginViewController.m
//  tcpoctest
//
//  Created by gump on 10/23/12.
//  Copyright (c) 2012 gump. All rights reserved.
//

#import "LoginViewController.h"
#import "WFLabel_blackShadow.h"
#import "ViewManager.h"
#import "netManager.h"
#import "RegexKitLite.h"

#import "DataBaseCtrol.h"
#import "DataControl.h"
#import "PromptLoginDataSource.h"
#import "TencentViewController.h"

#define BUTTON_HEIGHT 35
#define BUTTON_WIDTH 135

@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)init
{
    self = [super init];
    if (self)
    {
        mmailField = nil;
        mpsField = nil;
        mai = nil;
        iWaitTimer = 0;
        bStartLogin = false;
    }
    return self;
}

-(void)initUI
{
    
    bgScrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    bgScrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bgScrollView];
    
    UIImageView *backgoundImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    backgoundImage.image = [UIImage imageNamed:@"loginBg.JPG"];
    backgoundImage.userInteractionEnabled = YES;
    [bgScrollView addSubview:backgoundImage];
    
    UITapGestureRecognizer *singleTouch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyClick:)];
    singleTouch.delegate = self;
    [bgScrollView addGestureRecognizer:singleTouch];
    
    textLabel = [[FXLabel alloc] initWithFrame:CGRectMake(0, 70, 235, 50)];
    textLabel.text = [NSString stringWithFormat:@"欢迎使用%@",T_PROJECTNAME];
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:32.0];
    textLabel.textColor = [UIColor whiteColor];
    textLabel.backgroundColor = [UIColor colorWithRed:(216.f/255.f) green:(216.f/255.f) blue:(216.f/255.f) alpha:0.1];
    textLabel.shadowOffset = CGSizeMake(0.0f, 2.0f);
    textLabel.shadowColor = [UIColor colorWithWhite:0.0f alpha:0.75f];
    textLabel.shadowBlur = 5.0f;
    [backgoundImage addSubview:textLabel];
    
    //inputbg
    mailbgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nameInput.png"]];
    mailbgv.frame = CGRectMake(20, 180, 279, 44);
    mailbgv.userInteractionEnabled = YES;
    [backgoundImage addSubview:mailbgv];
    
    mmailField = [[UITextField alloc]initWithFrame:CGRectMake(50 , 0, 230, 44)];
    mmailField.backgroundColor = [UIColor clearColor];
    mmailField.font = [UIFont systemFontOfSize:17];
    mmailField.textColor = [UIColor blackColor];
    mmailField.clearButtonMode = UITextFieldViewModeWhileEditing;
    mmailField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    mmailField.placeholder = [NSString stringWithFormat:@"请输入账户/%@号",T_PROJECTNAME];
    mmailField.returnKeyType = UIReturnKeyNext;
    mmailField.tag = 0;
    mmailField.delegate = self;
    
    NSString *strppnum = [NSString stringWithFormat:@"%d",getLocalPP()];
    if (![strppnum isEqualToString:@"-1"]) {
        mmailField.text = strppnum;
    }
    
    [mailbgv addSubview:mmailField];
    
    psbgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"passwordInput.png"]];
    psbgv.frame = CGRectMake(20, 222,  279, 44);
    psbgv.userInteractionEnabled = YES;
    [backgoundImage addSubview:psbgv];
    
    mpsField = [[UITextField alloc]initWithFrame:CGRectMake(50, 0, 230, 44)];
    mpsField.backgroundColor = [UIColor clearColor];
    mpsField.font = [UIFont systemFontOfSize:17];;
    mpsField.clearButtonMode = UITextFieldViewModeWhileEditing;
    mpsField.textColor = [UIColor blackColor];
    mpsField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    mpsField.placeholder = T_PIPS;
    mpsField.returnKeyType = UIReturnKeyDone;
    mpsField.tag = 1;
    mpsField.delegate = self;
    mpsField.secureTextEntry = YES;
    [psbgv addSubview:mpsField];
    
    
    
    UIImage *btnimage = [UIImage imageNamed:@"loginButton.png"];
    UIButton *loginbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginbtn setBackgroundImage:btnimage forState:UIControlStateNormal];
    [loginbtn addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
    loginbtn.frame = CGRectMake(20, 290,  279, 35);
    [backgoundImage addSubview:loginbtn];
    
    //注册button
    UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    registerButton.backgroundColor = [UIColor colorWithRed:(216.f/255.f) green:(216.f/255.f) blue:(216.f/255.f) alpha:0.3];
    registerButton.frame = CGRectMake(20,335,BUTTON_WIDTH,BUTTON_HEIGHT);
    
    [registerButton setTitle:[NSString stringWithFormat:@"注册账号"] forState:UIControlStateNormal];
    [registerButton setTitleShadowColor:[UIColor colorWithWhite:0.0f alpha:0.75f] forState:UIControlStateNormal];
    registerButton.titleLabel.shadowOffset = CGSizeMake(0.0f, 2.0f);
    [registerButton addTarget:self action:@selector(configClick) forControlEvents:UIControlEventTouchUpInside];
    [registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backgoundImage addSubview:registerButton];
    
    
    //qq登录按钮
    UIButton * tencentOAuthButton = [UIButton buttonWithType:UIButtonTypeCustom];
    tencentOAuthButton.backgroundColor = [UIColor colorWithRed:(216.f/255.f) green:(216.f/255.f) blue:(216.f/255.f) alpha:0.3];
    tencentOAuthButton.frame = CGRectMake(30 + BUTTON_WIDTH,335,BUTTON_WIDTH,BUTTON_HEIGHT);
    [tencentOAuthButton setContentEdgeInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
    [tencentOAuthButton setTitle:[NSString stringWithFormat:@"QQ登陆"] forState:UIControlStateNormal];
    [tencentOAuthButton setTitleShadowColor:[UIColor colorWithWhite:0.0f alpha:0.75f] forState:UIControlStateNormal];
    tencentOAuthButton.titleLabel.shadowOffset = CGSizeMake(0.0f, 2.0f);
    [tencentOAuthButton addTarget:self action:@selector(onClickTencentOAuth) forControlEvents:UIControlEventTouchUpInside];
    [tencentOAuthButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backgoundImage addSubview:tencentOAuthButton];
    
    UIImageView * qqImageV = [[UIImageView alloc] initWithFrame:CGRectMake(20, 2, 31, 31)];
    qqImageV.image = [UIImage imageNamed:@"qq.png"];
    [tencentOAuthButton addSubview:qqImageV];
    
    
    
    
    
}

#pragma mark -private fun-
-(bool)CheckInput
{
    bool res = false;
    
    do
    {
        if(mmailField == nil)
        {
            break;
        }
        else if([mmailField.text length] == 0)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:
                                  [NSString stringWithFormat:@"用户名/%@号不能为空",T_PROJECTNAME]
                                                           delegate:self
                                                  cancelButtonTitle:@"确认"
                                                  otherButtonTitles:nil];
            [alert show];
            
            break;
            
        }
        else if([mpsField.text length] == 0)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"密码不能为空"
                                                           delegate:self
                                                  cancelButtonTitle:@"确认"
                                                  otherButtonTitles:nil];
            [alert show];
            
            break;
            
        }
        
        res = true;
        
    } while (false);
    
    return res;
}

-(void)LoginFail:(char)failID
{
    if(mai)
    {
        [mai stopAnimating];
        mai = nil;
    }
    
    bStartLogin = false;
    iWaitTimer = 0;
    
    switch (failID)
    {
        case LFM_MAIL:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:
                                  [NSString stringWithFormat:@"无此用户,请检查输入的用户名/%@号",T_PROJECTNAME]
                                                           delegate:self
                                                  cancelButtonTitle:@"确认"
                                                  otherButtonTitles:nil];
            [alert show];
        }
            break;
        case LFM_PS:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"密码不正确,请检查输入的密码"
                                                           delegate:self
                                                  cancelButtonTitle:@"确认"
                                                  otherButtonTitles:nil];
            [alert show];
        }
            break;
        case LFM_MAILLOCK:
        {
            [[ViewManager sharedViewManager] showFailHUDWithStatus:@"此账号被封"
                                                         withDelay:2
                                                          withView:self.view];
        }
            break;
        case LFM_DIVCELOCK:
        {
            [[ViewManager sharedViewManager] showFailHUDWithStatus:@"此设备被封"
                                                         withDelay:2
                                                          withView:self.view];
        }
            break;
        default:
            break;
    }
}

-(void)HideAI
{
    if(mai != nil)
    {
        [mai stopAnimating];
        mai = nil;
    }
}

-(void)hideKeyClick:(id)sender
{
    if([mmailField isFirstResponder] == YES)
    {
        [mmailField resignFirstResponder];
        [mpsField becomeFirstResponder];
    }
    else if([mpsField isFirstResponder] == YES)
    {
        [mpsField resignFirstResponder];
        [self downInputTextView];
    }
}

#pragma mark - btn selector
-(void)loginClick
{
    if ([self CheckInput])
    {
        NSString *ps = md5(mpsField.text);
        
        [DataControl shareControl].personDS.uinfo.mail = mmailField.text;
        [DataControl shareControl].personDS.uinfo.ps = ps;
        
        [[DataControl shareControl].promptloginDS SetIsShowMain:true];
        [[DataControl shareControl].promptloginDS SetIsPromptLogin:true];
        [[DataControl shareControl].promptloginDS SetIsInitData:true];
        
        if ([mmailField.text isMatchedByRegex:@"\\b(^\\d+$)\\b"])
        {
            [DataControl shareControl].personDS.uinfo.ppNumber = [mmailField.text integerValue];
            [[DataControl shareControl].LCDS addLogicCommand:LC_LOGINBYPP];
        }
        else
        {
            [[DataControl shareControl].LCDS addLogicCommand:LC_LOGINBYUI];
        }
        
        mai = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0,
                                                                        0,
                                                                        WINDOW_WIDTH, WINDOW_HIGTH)];
        [mai setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
        [self.view addSubview:mai];
        [mai startAnimating];
        bStartLogin = true;
    }
}

-(void)configClick
{
    [[ViewManager sharedViewManager] ClearConfigUI];
    
    [[ViewManager sharedViewManager] showView:VI_CONFIGFIRST
                             withIsRemoveCurV:true
                                withDirection:VD_RIGHT];
}



-(void)upInputTextView
{
    [bgScrollView setContentOffset:CGPointMake(0, 70) animated:YES];

}

-(void)downInputTextView
{
    [bgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark -textfield delegate-
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
            [mmailField resignFirstResponder];
            [mpsField becomeFirstResponder];
            break;
        case 1:
            [mpsField resignFirstResponder];
            [self downInputTextView];
            
            [self loginClick];
            break;
        default:
            break;
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    [self upInputTextView];
}

#pragma mark UIGestureRecognizerDelegate methods

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (([touch.view isDescendantOfView:self.view])&&([touch.view isKindOfClass:[UIButton class]])) {
        return NO;
    }
    return YES;
}


-(void)UICustomTick
{
    if(bStartLogin)
    {
        if(iWaitTimer > ACCESS_INTERVAL / 2)
        {
            [mai stopAnimating];
            bStartLogin = false;
            iWaitTimer = 0;
        }
        else
        {
            ++iWaitTimer;
        }
    }
}

-(void)SetMail:(NSString *)strmail
{
    if (mmailField == nil) {
        return;
    }
    
    mmailField.text = strmail;
}


#pragma mark - tencentOAuth
- (void)onClickTencentOAuth{
    TencentViewController * tencentWebVC = [[TencentViewController alloc] init];
    tencentWebVC.navigationTitle = @"QQ登陆";
    [self presentModalViewController:tencentWebVC animated:YES];
    
}



@end
